<template>
	<view class="store-select-page">
		<!-- 顶部导航栏 -->
		<!-- <view slot="right">
			<text class="common-fav">常用/收藏</text>
		</view> -->

		<!-- 城市选择 + 搜索栏 -->
		<view class="search-bar">
			<view class="city-picker">
				<text class="city-text">{{ city }}</text>
				<u-icon name="arrow-down" size="16"></u-icon>
			</view>
			<u-search placeholder="搜索门店/地址" :show-action="false" @search="onSearch"></u-search>
			<text class="search-btn" @click="onSearch">搜索</text>
		</view>

		<!-- 地图展示 -->
		<view class="map-wrap">
			<map style="width: 100%; height: 300px;" :latitude="latitude" :longitude="longitude" :markers="covers" :scale="15"
				@markertap="onMarkerTap">
			</map>
		</view>

		<!-- 门店列表 -->
		<view class="store-list">
			<view class="store-item" v-for="(item, index) in storeList" :key="index">
				<view class="store-info">
					<view class="store-name">
						<u-icon name="star" color="#FFD700" size="16"></u-icon>
						{{ item.name }}
					</view>
					<text class="store-address">{{ item.address }}</text>
					<text class="store-time">{{ item.businessHours }}</text>
				</view>
				<view class="store-extra">
					<text class="store-distance">{{ item.distance }}</text>
					<view class="store-actions">
						<u-icon name="phone" size="20" @click="() => callPhone(item.phone)"></u-icon>
						<u-icon name="arrow-right" size="20" @click="() => navigateTo(item.id)"></u-icon>
					</view>
				</view>
			</view>

			<!-- 无数据状态 -->
			<view class="empty-list" v-if="storeList.length === 0">
				<text>暂无附近门店</text>
			</view>
		</view>

		<!-- 去下单按钮 -->
		<view class="order-btn" @click="goToOrder">
			去下单
		</view>
	</view>
</template>

<script>
	// 引入腾讯地图SDK
	const QQMapWX = require('../../libs/map-sdk/qqmap-wx-jssdk.js');

	export default {
		data() {
			return {
				// 定义初始经纬度
				latitude: 39.909,
				longitude: 116.39742,
				city: '深圳市',
				qqmapsdk: null,
				covers: [],
				storeList: [],
				loading: false
			};
		},
		onLoad() {
			// 初始化腾讯地图SDK
			this.qqmapsdk = new QQMapWX({
				key: 'JRFBZ-L5Y63-WUK3N-ODVMQ-47X2Z-7IFXE' // 替换为你的Key
			});
			// 获取当前位置，获取经纬度的方法
			this.getLocation();
		},
		methods: {
			// 获取当前位置
			getLocation() {
				this.loading = true;

				// 检查权限
				uni.getSetting({
					success: (res) => {
						if (!res.authSetting['scope.userLocation']) {
							// 未授权，请求权限
							uni.authorize({
								scope: 'scope.userLocation',
								success: () => {
									// 权限通过，获取位置
									this._getLocation();
								},
								fail: () => {
									// 用户拒绝，提示并使用默认位置
									uni.showToast({
										title: '需要位置权限才能获取附近门店',
										icon: 'none'
									});
									this.loading = false;
									this.initDefaultStores(); // 使用默认门店数据
								}
							});
						} else {
							// 已授权，直接获取位置
							this._getLocation();
						}
					}
				});
			},

			// 实际获取位置的方法
			_getLocation() {
				uni.getLocation({
					type: 'gcj02', // 腾讯地图使用gcj02坐标系，只有腾讯地图才兼容微信小程序
					success: (res) => {
						console.log(res, '1111111111111111111111111111')
						// 更新当前位置
						this.latitude = res.latitude;
						this.longitude = res.longitude;

						// 更新标记点，添加当前位置标记
						this.covers = [{
							id: 0,
							latitude: res.latitude,
							longitude: res.longitude,
							iconPath: '/static/current-location.png',
							width: 30, // 添加宽度
							height: 30, // 添加高度
							title: '当前位置'
						}];

						// 解析地址信息,通过经纬度，去逆解析，出省市区和地点
						this.reverseGeocoder(res.latitude, res.longitude);

						// 获取附近门店
						this.getNearbyStores(res.latitude, res.longitude);
					},
					fail: (err) => {
						console.error('获取位置失败:', err);
						uni.showToast({
							title: '获取位置失败，请检查权限',
							icon: 'none'
						});
						this.loading = false;
						this.initDefaultStores(); // 使用默认门店数据
					}
				});
			},

			// 逆地址解析（经纬度转地址）
			reverseGeocoder(latitude, longitude) {
				this.qqmapsdk.reverseGeocoder({
					location: {
						latitude: latitude,
						longitude: longitude
					},
					success: (res) => {
						console.log('地址解析成功:', res);
						this.city = res.result.address_component.city;
					},
					fail: (err) => {
						console.error('地址解析失败:', err);
					}
				});
			},

			// 获取附近门店（模拟数据）
			getNearbyStores(latitude, longitude) {
				// 实际项目中应该调用后端API获取附近门店
				// 这里使用模拟数据

				// 模拟计算距离（实际应通过经纬度计算）
				const calculateDistance = (lat1, lng1, lat2, lng2) => {
					// 简化的距离计算（非真实算法）
					const dx = Math.abs(lat1 - lat2) * 111;
					const dy = Math.abs(lng1 - lng2) * 111;
					return Math.sqrt(dx * dx + dy * dy).toFixed(2);
				};

				// 模拟门店数据
				this.storeList = [{
						id: 1,
						name: '福田深圳之眼店',
						address: '广东省深圳市福田区深南大道2006路深圳之眼商场C1-03',
						businessHours: '09:30-23:00',
						distance: `${calculateDistance(latitude, longitude, 22.543099, 114.057868)}km`,
						phone: '400-123-4567',
						latitude: 22.543099,
						longitude: 114.057868
					},
					{
						id: 2,
						name: '华强北茂业天地店',
						address: '广东省深圳市福田区华强北茂业天地XX号',
						businessHours: '09:00-22:00',
						distance: `${calculateDistance(latitude, longitude, 22.548099, 114.067868)}km`,
						phone: '400-123-4568',
						latitude: 22.548099,
						longitude: 114.067868
					},
					{
						id: 3,
						name: '南山科技园店',
						address: '广东省深圳市南山区科技园南区XX大厦',
						businessHours: '08:30-22:30',
						distance: `${calculateDistance(latitude, longitude, 22.533099, 114.047868)}km`,
						phone: '400-123-4569',
						latitude: 22.533099,
						longitude: 114.047868
					}
				];

				// 添加门店标记
				this.storeList.forEach((store, index) => {
					this.covers.push({
						id: index + 1,
						latitude: store.latitude,
						longitude: store.longitude,
						iconPath: '/static/location.png',
						width: 30,
						height: 30,
						title: store.name
					});
				});

				this.loading = false;
			},

			// 使用默认门店数据
			initDefaultStores() {
				// 使用北京的默认位置和门店数据
				this.latitude = 39.909;
				this.longitude = 116.39742;
				this.city = '北京市';

				this.covers = [{
					id: 0,
					latitude: 39.909,
					longitude: 116.39742,
					iconPath: '/static/current-location.png',
					width: 30,
					height: 30,
					title: '默认位置'
				}];

				this.storeList = [{
						id: 1,
						name: '北京王府井店',
						address: '北京市东城区王府井大街123号',
						businessHours: '10:00-22:00',
						distance: '1.2km',
						phone: '010-12345678'
					},
					{
						id: 2,
						name: '北京国贸店',
						address: '北京市朝阳区国贸中心三期',
						businessHours: '09:30-22:30',
						distance: '3.5km',
						phone: '010-12345679'
					}
				];

				// 添加默认门店标记
				this.storeList.forEach((store, index) => {
					this.covers.push({
						id: index + 1,
						latitude: 39.909 - 0.01 * index,
						longitude: 116.39742 + 0.01 * index,
						iconPath: '/static/location.png',
						width: 30,
						height: 30,
						title: store.name
					});
				});
			},

			// 搜索处理
			onSearch() {
				// 实现搜索逻辑
				uni.showToast({
					title: '搜索功能待实现',
					icon: 'none'
				});
			},

			// 标记点击事件
			onMarkerTap(e) {
				// 处理标记点击
				console.log('标记点击:', e);
			},

			// 拨打电话
			callPhone(phone) {
				uni.makePhoneCall({
					phoneNumber: phone
				});
			},

			// 导航到门店详情
			navigateTo(storeId) {
				// 跳转到门店详情页
				uni.navigateTo({
					url: `/pages/store/detail?id=${storeId}`
				});
			},

			// 去下单
			goToOrder() {
				// 跳转到下单页
				uni.navigateTo({
					url: '/pages/order/index'
				});
			}
		}
	};
</script>

<style scoped lang="scss">
	.store-select-page {
		background-color: #fff;
		height: 100%;
		overflow-y: auto;

		// 搜索栏
		.search-bar {
			display: flex;
			align-items: center;
			padding: 10px 15px;
			background-color: #f8f8f8;

			.city-picker {
				display: flex;
				align-items: center;
				background-color: #fff;
				padding: 5px 10px;
				border-radius: 4px;
				margin-right: 10px;

				.city-text {
					font-size: 14px;
					color: #333;
				}
			}

			.search-btn {
				font-size: 14px;
				color: #007aff;
				margin-left: 10px;
			}
		}

		// 地图容器
		.map-wrap {
			width: 100%;
			height: 300px;
			position: relative;
		}

		// 门店列表
		.store-list {
			padding: 10px 15px;

			.store-item {
				display: flex;
				padding: 15px;
				background-color: #fff;
				border-radius: 8px;
				margin-bottom: 10px;
				box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

				.store-info {
					flex: 1;

					.store-name {
						font-size: 16px;
						color: #333;
						font-weight: bold;
						display: flex;
						align-items: center;

						::v-deep .u-icon {
							margin-right: 5px;
						}
					}

					.store-address {
						font-size: 14px;
						color: #666;
						margin-top: 5px;
						display: block;
					}

					.store-time {
						font-size: 12px;
						color: #999;
						margin-top: 3px;
						display: block;
					}
				}

				.store-extra {
					display: flex;
					flex-direction: column;
					align-items: flex-end;

					.store-distance {
						font-size: 12px;
						color: #999;
						margin-bottom: 5px;
					}

					.store-actions {
						display: flex;
						gap: 10px;

						::v-deep .u-icon {
							color: #999;
						}
					}
				}
			}

			.empty-list {
				padding: 50px 0;
				text-align: center;
				color: #999;
			}
		}

		// 去下单按钮
		.order-btn {
			position: fixed;
			bottom: 0px;
			left: 15px;
			right: 15px;
			background-color: #f5b041;
			color: #fff;
			font-size: 16px;
			text-align: center;
			padding: 12px 0;
			border-radius: 8px;
			margin-bottom: 15px;
			z-index: 100;
		}
	}
</style>